package cn.devices.security;

import cn.devices.mapper.TbAdmMapper;
import cn.devices.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
    @Value("${load.upload}")
    private String uploadPath;
    @Autowired
    private AuthUserService userDetailService;
    @Autowired
    TbAdmMapper mapper;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/tb-adm/admAdd").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-borrow/borrowDtoList").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-user/androidUserDto").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-user/tbUserGetById").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-user/imgInfo").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-borrow/isBorrow").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-borrow/borrowS").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-borrow/getUserIdBorrow").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-type/tbTypeList").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-task/tbTaskAdd").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-task/tbTaskUpdate").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-task/getByTaskList").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-task/deviceDtoList").permitAll()
                .antMatchers(HttpMethod.POST, "/tb-borrow/isRecycle").permitAll()
                .antMatchers(HttpMethod.POST, "/tb-device/tbDevicesAdd").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-device/getNotRegister").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-device/getByCode").permitAll()
                .antMatchers(HttpMethod.POST, "/tb-device/tbDeviceUpdate").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-device/getRegister").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-device/tbDevice").permitAll()
                .antMatchers(HttpMethod.GET, "/tb-device/deviceStatus").permitAll()
                .antMatchers(HttpMethod.POST, "/tb-inventory/tbInventoryAdd").permitAll()
                .antMatchers(HttpMethod.POST, "/tb-event/eventAdd").permitAll()
                .antMatchers("/static/images/**").permitAll()

                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTLoginFilter(authenticationManager()))
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new JWTAuthenticationEntryPoint());

    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/images/user/**").addResourceLocations("file:" + uploadPath + File.separator + "user" + File.separator);
        registry.addResourceHandler("/static/images/devices/**").addResourceLocations("file:" + uploadPath + File.separator + "devices" + File.separator);
        registry.addResourceHandler("/static/images/borrow/**").addResourceLocations("file:" + uploadPath + File.separator + "borrow" + File.separator);
        registry.addResourceHandler("/static/images/back/**").addResourceLocations("file:" + uploadPath + File.separator + "back" + File.separator);
        //和页面有关的静态目录都放在项目的static目录下
        //registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //上传的图片在D盘下的OTA目录下，访问路径如：http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
        //其中OTA表示访问的前缀。"file:D:/OTA/"是文件真实的存储路径
        // registry.addResourceHandler(uploadPath + File.separator + "user" + "/**").addResourceLocations("file:" + uploadPath + File.separator + "user" + File.separator);
    }

}
